package com.aviator.detective.common.reflect;

import javassist.*;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;

import java.io.IOException;

public class JavassistUtil {

        public static void addAnnotationOnAllMethod(String fullQualifiedClassName,Class annotationClass) throws NotFoundException,CannotCompileException, IOException{
            ClassPool pool = ClassPool.getDefault();
            CtClass ctClass = pool.get(fullQualifiedClassName);
            CtMethod[] methods = ctClass.getMethods();
            for (CtMethod method : methods) {
                addAnnotationOnMethod(ctClass,method,annotationClass);
            }
        }

        public static void addAnnotationOnMethod(CtClass ctClass,CtMethod method,Class annotationClass) throws CannotCompileException, IOException, NotFoundException {
            ctClass.defrost();
            ClassFile classFile = ctClass.getClassFile();
            ConstPool constPool = classFile.getConstPool();
            AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool,AnnotationsAttribute.visibleTag);
            Annotation annotation = new Annotation(annotationClass.getCanonicalName(),constPool);
            annotationsAttribute.addAnnotation(annotation);
            method.getMethodInfo().addAttribute(annotationsAttribute);
            ctClass.writeFile();
        }
}
